<?php

class ImportController extends \Phalcon\Mvc\Controller {

    public function indexAction() {
        
    }

    public function importQuestionsAction() {
        if ($this->request->hasFiles()) {
            foreach ($this->request->getUploadedFiles() as $file) {
                $data = $this->getFileXls(null, $file->getTempName(), 2);
                echo '<pre>';
                foreach ($data as $value){
                    $question = new Questions();
                    $question->assign(array(
                        'question' => $value[1],
                        'answerA' => $value[2],
                        'answerB' => $value[3],
                        'answerC' => $value[4],
                        'answerD' => $value[5],
                        'correct' => $value[6],
                        'level' => $value[7],
                        'reference' => $value[8],
                        'audio' => $value[9],
                        'position' => $value[10],
                        'difficult' => $value[11],
                        'part' => $value[12],
                    ));
                    print_r($question->toArray());
                    if(!$question->save()){
                        print_r($question->getMessages());
                    }
                }
            }
            die();
        }
        
    }

    private function getFileXls($data = null, $filename = null, $minRow = 1) {
        //load library
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');

        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($filename);

        $rowIterator = $objPHPExcel->getSheet(0)->getRowIterator();
        foreach ($rowIterator as $row) {
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false); 
            $rowIndex = $row->getRowIndex();

            if ($minRow > $rowIndex)
                continue;

            foreach ($cellIterator as $key => $value) {
                $data[$rowIndex][$key] = $value->getCalculatedValue();
            }
        }
        return $data;
    }

}
